import {messages} from "share/common";
import React, { Component } from 'react';
import { Form, Button } from 'antd'
import AdvancedSearchFormItem from 'components/advanced-search/advanced-search-form-item'
import 'styles/components/advanced-table/advanced-table-filter-dropdown.scss'
import { formatValue } from "components/advanced-search/utils";

class AdvancedTableFilterDropdown extends Component {

  componentDidMount(){
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  getFormField = field => {
    const { form } = this.props;
    return <AdvancedSearchFormItem
      form={form}
      field={field}
    />
  };

  search = noTrigger => {
    const { form, onSearch, searchForm } = this.props;
    return new Promise(resolve => {
      form.validateFields((error, values) => {
        if(!error) {
          let target = formatValue(values, searchForm);
          if(noTrigger === true) {
            resolve([target, values]);
          } else {
            onSearch && onSearch(target, values);
          }
        }
      });
    })
  };

  reset = () => {
    const { form } = this.props;
    form.resetFields();
  };

  render() {
    const { searchForm } = this.props;
    return (
      <div className='advanced-table-filter-dropdown'>
        <Form layout='horizontal'>
          {searchForm.map(this.getFormField)}
        </Form>
        <div className='advanced-table-filter-dropdown-buttons'>
          <Button onClick={this.reset}>{messages('common.reset')/*重置*/}</Button>
          <Button type='primary' onClick={this.search}>{messages('common.ok')/*确定*/}</Button>
        </div>
      </div>
    );
  }
}

export default Form.create()(AdvancedTableFilterDropdown);
